<!DOCTYPE html>
<html lang=zh>
<head>
    <!-- so meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="HandheldFriendly" content="True">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5" />
    <meta name="description" content="在JavaScript中，函数是第一公民，因此JavaScript符合函数式编程（Functional Programming）的范式，在函数式编程中，有很多概念，我们先从纯函数说起。 纯函数（pure function）对于纯函数来说，维基百科是这样定义的：  在程序设计中，若一个函数符合以下条件，那么这个函数被称为纯函数： 此函数在相同的输入值时，需产生相同的输出。  函数的输出和输入值以外的">
<meta property="og:type" content="article">
<meta property="og:title" content="函数式编程">
<meta property="og:url" content="https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/index.html">
<meta property="og:site_name" content="柯里的语法糖">
<meta property="og:description" content="在JavaScript中，函数是第一公民，因此JavaScript符合函数式编程（Functional Programming）的范式，在函数式编程中，有很多概念，我们先从纯函数说起。 纯函数（pure function）对于纯函数来说，维基百科是这样定义的：  在程序设计中，若一个函数符合以下条件，那么这个函数被称为纯函数： 此函数在相同的输入值时，需产生相同的输出。  函数的输出和输入值以外的">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-02-05T06:19:40.054Z">
<meta property="article:modified_time" content="2022-02-05T06:19:40.054Z">
<meta property="article:author" content="柯里的语法糖">
<meta property="article:tag" content="JavaScript">
<meta name="twitter:card" content="summary">
    
    
      
        
          <link rel="shortcut icon" href="https://codertzm.oss-cn-chengdu.aliyuncs.com/favicon.ico">
        
      
      
        
          <link rel="icon" type="image/png" href="https://codertzm.oss-cn-chengdu.aliyuncs.com/favicon.ico" sizes="192x192">
        
      
      
        
          <link rel="apple-touch-icon" sizes="180x180" href="https://codertzm.oss-cn-chengdu.aliyuncs.com/favicon.ico">
        
      
    
    <!-- title -->
    <title>函数式编程</title>
    <!-- styles -->
    
<link rel="stylesheet" href="/css/style.css">

    <!-- persian styles -->
    
    <!-- rss -->
    
    
	<!-- mathjax -->
	
<meta name="generator" content="Hexo 6.0.0"></head>

<body class="max-width mx-auto px3 ltr">
    
      <div id="header-post">
  <a id="menu-icon" href="#" aria-label="Menu"><i class="fas fa-bars fa-lg"></i></a>
  <a id="menu-icon-tablet" href="#" aria-label="Menu"><i class="fas fa-bars fa-lg"></i></a>
  <a id="top-icon-tablet" href="#" aria-label="Top" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');" style="display:none;"><i class="fas fa-chevron-up fa-lg"></i></a>
  <span id="menu">
    <span id="nav">
      <ul>
        <!--
       --><li><a href="/">首页</a></li><!--
     --><!--
       --><li><a href="/tags/">标签</a></li><!--
     --><!--
       --><li><a href="/categories/">分类</a></li><!--
     --><!--
       --><li><a href="/archives/">归档</a></li><!--
     --><!--
       --><li><a target="_blank" rel="noopener" href="http://github.com/twitzz">项目</a></li><!--
     --><!--
       --><li><a href="/about/">关于</a></li><!--
     --><!--
       --><li><a href="/search/">搜索</a></li><!--
     -->
      </ul>
    </span>
    <br/>
    <span id="actions">
      <ul>
        
        <li><a class="icon" aria-label="上一篇" href="/2022/02/05/JavaScript/reactive/"><i class="fas fa-chevron-left" aria-hidden="true" onmouseover="$('#i-prev').toggle();" onmouseout="$('#i-prev').toggle();"></i></a></li>
        
        
        <li><a class="icon" aria-label="下一篇" href="/2022/02/05/JavaScript/debounce/"><i class="fas fa-chevron-right" aria-hidden="true" onmouseover="$('#i-next').toggle();" onmouseout="$('#i-next').toggle();"></i></a></li>
        
        <li><a class="icon" aria-label="返回顶部" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up" aria-hidden="true" onmouseover="$('#i-top').toggle();" onmouseout="$('#i-top').toggle();"></i></a></li>
        <li><a class="icon" aria-label="分享文章" href="#"><i class="fas fa-share-alt" aria-hidden="true" onmouseover="$('#i-share').toggle();" onmouseout="$('#i-share').toggle();" onclick="$('#share').toggle();return false;"></i></a></li>
      </ul>
      <span id="i-prev" class="info" style="display:none;">上一篇</span>
      <span id="i-next" class="info" style="display:none;">下一篇</span>
      <span id="i-top" class="info" style="display:none;">返回顶部</span>
      <span id="i-share" class="info" style="display:none;">分享文章</span>
    </span>
    <br/>
    <div id="share" style="display: none">
      <ul>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.facebook.com/sharer.php?u=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/"><i class="fab fa-facebook " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://twitter.com/share?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&text=函数式编程"><i class="fab fa-twitter " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.linkedin.com/shareArticle?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&title=函数式编程"><i class="fab fa-linkedin " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://pinterest.com/pin/create/bookmarklet/?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&is_video=false&description=函数式编程"><i class="fab fa-pinterest " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=函数式编程&body=Check out this article: https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/"><i class="fas fa-envelope " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://getpocket.com/save?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&title=函数式编程"><i class="fab fa-get-pocket " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://reddit.com/submit?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&title=函数式编程"><i class="fab fa-reddit " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.stumbleupon.com/submit?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&title=函数式编程"><i class="fab fa-stumbleupon " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://digg.com/submit?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&title=函数式编程"><i class="fab fa-digg " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.tumblr.com/share/link?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&name=函数式编程&description="><i class="fab fa-tumblr " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://news.ycombinator.com/submitlink?u=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&t=函数式编程"><i class="fab fa-hacker-news " aria-hidden="true"></i></a></li>
</ul>

    </div>
    <div id="toc">
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BA%AF%E5%87%BD%E6%95%B0%EF%BC%88pure-function%EF%BC%89"><span class="toc-number">1.</span> <span class="toc-text">纯函数（pure function）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BA%AF%E5%87%BD%E6%95%B0%E7%9A%84%E4%BC%98%E5%8A%BF"><span class="toc-number">2.</span> <span class="toc-text">纯函数的优势</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E6%9F%AF%E9%87%8C%E5%8C%96%EF%BC%88curry%EF%BC%89"><span class="toc-number">3.</span> <span class="toc-text">函数柯里化（curry）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%95%E4%B8%80%E8%81%8C%E8%B4%A3%EF%BC%88%E5%87%BD%E6%95%B0%E6%9F%AF%E9%87%8C%E5%8C%96%E7%9A%84%E4%BD%9C%E7%94%A8%EF%BC%89"><span class="toc-number">4.</span> <span class="toc-text">单一职责（函数柯里化的作用）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E6%9F%AF%E9%87%8C%E5%8C%96%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">5.</span> <span class="toc-text">函数柯里化的实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E7%BB%84%E5%90%88%EF%BC%88compose%EF%BC%89"><span class="toc-number">6.</span> <span class="toc-text">代码组合（compose）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A3%B0%E6%98%8E%E5%BC%8F%E7%9A%84%E4%BB%A3%E7%A0%81"><span class="toc-number">7.</span> <span class="toc-text">声明式的代码</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">8.</span> <span class="toc-text">总结</span></a></li></ol>
    </div>
  </span>
</div>

    
    <div class="content index py4">
        
        <article class="post" itemscope itemtype="http://schema.org/BlogPosting">
  <header>
    
    <h1 class="posttitle" itemprop="name headline">
        函数式编程
    </h1>



    <div class="meta">
      <span class="author" itemprop="author" itemscope itemtype="http://schema.org/Person">
        <span itemprop="name">柯里的语法糖</span>
      </span>
      
    <div class="postdate">
      
        <time datetime="2022-02-05T06:19:40.054Z" itemprop="datePublished">2022-02-05</time>
        
      
    </div>


      
    <div class="article-category">
        <i class="fas fa-archive"></i>
        <a class="category-link" href="/categories/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/">前端基础</a>
    </div>


      
    <div class="article-tag">
        <i class="fas fa-tag"></i>
        <a class="tag-link-link" href="/tags/JavaScript/" rel="tag">JavaScript</a>
    </div>


    </div>
  </header>
  

  <div class="content" itemprop="articleBody">
    <p>在JavaScript中，函数是第一公民，因此JavaScript符合函数式编程（Functional Programming）的范式，在函数式编程中，有很多概念，我们先从纯函数说起。</p>
<h2 id="纯函数（pure-function）"><a href="#纯函数（pure-function）" class="headerlink" title="纯函数（pure function）"></a>纯函数（pure function）</h2><p>对于纯函数来说，维基百科是这样定义的：</p>
<blockquote>
<p>在程序设计中，若一个函数符合以下条件，那么这个函数被称为纯函数：</p>
<p>此函数在相同的输入值时，需产生相同的输出。 </p>
<p>函数的输出和输入值以外的其他隐藏信息或状态无关，也和由I/O设备产生的外部输出无关。</p>
<p>该函数不能有语义上可观察的函数副作用，诸如“触发事件”，使输出设备输出，或更改输出值以外物件的内容等</p>
</blockquote>
<p>简单理解来说，对于一个函数，当它的<strong>确定的输入产生了确定的输出</strong>，并且在函数执行的过程中，没有产生<strong>副作用</strong>，那么这个函数就是纯函数。</p>
<p><strong>什么又是副作用呢？</strong></p>
<p>在计算机科学中，副作用表示在执行一个函数的时候，除了返回函数值之外，还对调用函数产生了附加的影响，比如修改了全局变量，修改了参数等等…</p>
<p>在了解了纯函数的概念后，我们来看看下面这几个函数是否是纯函数：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">num1, num2</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> num1 + num2</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> foo = <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">num</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 函数依赖了全局变量</span></span><br><span class="line">    <span class="keyword">return</span> foo + num</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bar</span>(<span class="params">info</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 函数修改了全局变量，产生了副作用</span></span><br><span class="line">    info.name = <span class="string">&#x27;codertzm&#x27;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>很明显，函数<code>sum</code>是纯函数，而<code>add</code>函数和<code>bar</code>函数都不是纯函数，因为<code>add</code>函数依赖了全局变量导致了<strong>不确定的输出</strong>，<code>bar</code>函数修改了全局变量导致了<strong>副作用</strong>。</p>
<h2 id="纯函数的优势"><a href="#纯函数的优势" class="headerlink" title="纯函数的优势"></a>纯函数的优势</h2><p>为什么说纯函数对于函数式编程如此重要呢？</p>
<ol>
<li>可以让程序员安心的使用这个函数</li>
<li>只关心业务逻辑，不需要关心传入的内容是如何获得的或者是依赖于其他外部的变量</li>
</ol>
<p>像React这样的推崇函数式编程的前端框架，就要求我们在封装组件的时候，这个组件必须像纯函数一样，不让它们的props被修改。</p>
<h2 id="函数柯里化（curry）"><a href="#函数柯里化（curry）" class="headerlink" title="函数柯里化（curry）"></a>函数柯里化（curry）</h2><p>函数柯里化是函数式编程的一个重要概念，它可以提高函数使用的灵活度，增加参数的复用</p>
<p>函数柯里化的定义是一种将使用<strong>接收多个参数的一个函数</strong>转换成<strong>接受一个单一参数</strong>（最初函数的第一个参数）的函数，并且<strong>返回接受余下的参数</strong>，而且返回结果的是新函数的技术。</p>
<p><strong>或者可以说成</strong>：只传递给函数一部分参数来调用它，让它返回一个函数去处理剩下的参数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> add = <span class="function"><span class="keyword">function</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">y</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> x + y;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> addOne = add(<span class="number">1</span>);</span><br><span class="line"><span class="keyword">var</span> addTen = add(<span class="number">10</span>);</span><br><span class="line"></span><br><span class="line">addOne(<span class="number">2</span>); <span class="comment">// 3</span></span><br><span class="line"></span><br><span class="line">addTen(<span class="number">2</span>); <span class="comment">// 10</span></span><br></pre></td></tr></table></figure>

<p>这里我们定义了一个 <code>add </code>函数，它接受一个参数并返回一个新的函数。调用 <code>add </code>之后，返回的函数就通过闭包的方式记住了 <code>add</code> 的第一个参数。</p>
<h2 id="单一职责（函数柯里化的作用）"><a href="#单一职责（函数柯里化的作用）" class="headerlink" title="单一职责（函数柯里化的作用）"></a>单一职责（函数柯里化的作用）</h2><p>我们了解了函数柯里化是什么东西后，可能会有这样的疑问：<strong>函数为什么需要柯里化？</strong></p>
<p>在设计模式里，有一种原则叫<strong>单一职责原则（Single Responsibility Principle）</strong>，它具体表现为一个对象（方法）只做一件事情。</p>
<p>而函数柯里化其实就是将每次传入的参数<strong>在单一的函数</strong>中进行处理，处理完后在<strong>下一个函数</strong>中再使用处理后的结果。</p>
<p>比如在上面的例子中，我们先实现了一个加1的方法，再将想要加1的那个数字传递给下一个函数作为参数。</p>
<p>并且，函数柯里化还可以<strong>帮助我们复用参数逻辑</strong>。</p>
<p>同样在上面的例子中，我们实现了加1这个方法后，可以无限的复用这个逻辑。</p>
<h2 id="函数柯里化的实现"><a href="#函数柯里化的实现" class="headerlink" title="函数柯里化的实现"></a>函数柯里化的实现</h2><p>接下来我们来实现函数柯里化。</p>
<p>通过上面的例子其实我们能够想到，柯里化函数一定是有<strong>递归调用</strong>的，且<strong>返回值一定是个函数</strong>，因此我们可以通过判断实参与形参的个数来判断是否继续递归调用</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">myCurry</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">curry</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 判断接收的参数的个数是否大于需要传入的参数</span></span><br><span class="line">    <span class="keyword">if</span> (args.length &gt;= fn.length) &#123;</span><br><span class="line">      <span class="keyword">return</span> fn.apply(<span class="built_in">this</span>, args)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 没有达到个数时，返回一个新的函数，继续接受参数，其实就是收集参数的过程</span></span><br><span class="line">      <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> (<span class="params">...restArgs</span>) </span>&#123;</span><br><span class="line">        <span class="comment">// 防止this出现问题</span></span><br><span class="line">        <span class="keyword">return</span> curry.apply(<span class="built_in">this</span>, [...args,...restArgs])</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> curry</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实现柯里化函数后，我们来看看结果</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">a, b, c, d</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> a + b + c + d</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> curryFoo = myCurry(foo)</span><br><span class="line">curryFoo(<span class="number">1</span>,<span class="number">3</span>)(<span class="number">4</span>)(<span class="number">5</span>) <span class="comment">// 13</span></span><br></pre></td></tr></table></figure>

<p>至此，我们就实现了函数柯里化。</p>
<h2 id="代码组合（compose）"><a href="#代码组合（compose）" class="headerlink" title="代码组合（compose）"></a>代码组合（compose）</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> compose = <span class="function"><span class="keyword">function</span>(<span class="params">f,g</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> f(g(x));</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>这其实就是一个简单的组合函数，<code>f</code>和<code>g</code>都是函数，<code>x</code> 是在它们之间通过“管道”传输的值。</p>
<p>代码组合其实就是一种对函数使用的技巧，它可以将两个依次执行的函数通过代码组合起来，自动依次调用。</p>
<p>接下来我们来实现一个比较复杂的组合函数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">myCompose</span>(<span class="params">...fns</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> length = fns.length</span><br><span class="line">  <span class="comment">// 判断传入的参数是否都是函数</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; length; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> fns[i] !== <span class="string">&#x27;function&#x27;</span>) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">&#x27;Expected arguments are functions&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">compose</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> index = <span class="number">0</span></span><br><span class="line">    <span class="comment">// 第一个参数的返回值</span></span><br><span class="line">    <span class="keyword">var</span> result = length ? fns[index].apply(<span class="built_in">this</span>, args) : args</span><br><span class="line">    <span class="keyword">while</span> (++index &lt; length) &#123;</span><br><span class="line">      <span class="comment">// 将上一次的结果作为这次的参数传入</span></span><br><span class="line">      result = fns[index].call(<span class="built_in">this</span>, result)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line">  &#125;</span><br><span class="line">    </span><br><span class="line">  <span class="keyword">return</span> compose</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>至此，我们可以使用这个myCompose函数进行将多个函数进行组合调用。</p>
<h2 id="声明式的代码"><a href="#声明式的代码" class="headerlink" title="声明式的代码"></a>声明式的代码</h2><p>在函数式编程中，由于函数是第一公民，因此我们需要使用<strong>声明式的代码</strong>而非<strong>命令式的代码。</strong></p>
<p>与命令式代码不同，声明式代码要求更多的使用表达式。    </p>
<p>来看看声明式代码和命令式代码的比较：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> makes = [];</span><br><span class="line"><span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; cars.length; i++) &#123;</span><br><span class="line">  makes.push(cars[i].make);</span><br><span class="line">&#125;	</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> makes = cars.map(<span class="function"><span class="keyword">function</span>(<span class="params">car</span>)</span>&#123; <span class="keyword">return</span> car.make; &#125;);</span><br></pre></td></tr></table></figure>

<p>很明显的是：</p>
<p>命令式的循环要求必须先实例化一个数组，而且执行完这个实例化语句之后，解释器才继续执行后面的代码。</p>
<p>声明式的代码使用 <code>map</code> 函数，它是一个表达式，它对执行顺序没有要求。而且，<code>map</code> 函数如何进行迭代，返回的数组如何收集，都有很大的自由度。它指明的是<code>做什么</code>，不是<code>怎么做</code>。</p>
<p>声明式的代码除了更加简洁和清晰以外，<code>map</code>函数还可以进一步被优化，这就是函数式编程的优势。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>关于函数式编程还有其他可以说的内容，比如范畴学、函子等，本篇文章只是作为函数式编程的入门，关于函数式编程的库也有很多，如：lodash、rxjs等，大家可以去使用并阅读它们的源码去学习。</p>

  </div>
</article>



        
          <div id="footer-post-container">
  <div id="footer-post">

    <div id="nav-footer" style="display: none">
      <ul>
         
          <li><a href="/">首页</a></li>
         
          <li><a href="/tags/">标签</a></li>
         
          <li><a href="/categories/">分类</a></li>
         
          <li><a href="/archives/">归档</a></li>
         
          <li><a target="_blank" rel="noopener" href="http://github.com/twitzz">项目</a></li>
         
          <li><a href="/about/">关于</a></li>
         
          <li><a href="/search/">搜索</a></li>
        
      </ul>
    </div>

    <div id="toc-footer" style="display: none">
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BA%AF%E5%87%BD%E6%95%B0%EF%BC%88pure-function%EF%BC%89"><span class="toc-number">1.</span> <span class="toc-text">纯函数（pure function）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BA%AF%E5%87%BD%E6%95%B0%E7%9A%84%E4%BC%98%E5%8A%BF"><span class="toc-number">2.</span> <span class="toc-text">纯函数的优势</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E6%9F%AF%E9%87%8C%E5%8C%96%EF%BC%88curry%EF%BC%89"><span class="toc-number">3.</span> <span class="toc-text">函数柯里化（curry）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%95%E4%B8%80%E8%81%8C%E8%B4%A3%EF%BC%88%E5%87%BD%E6%95%B0%E6%9F%AF%E9%87%8C%E5%8C%96%E7%9A%84%E4%BD%9C%E7%94%A8%EF%BC%89"><span class="toc-number">4.</span> <span class="toc-text">单一职责（函数柯里化的作用）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E6%9F%AF%E9%87%8C%E5%8C%96%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">5.</span> <span class="toc-text">函数柯里化的实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E7%BB%84%E5%90%88%EF%BC%88compose%EF%BC%89"><span class="toc-number">6.</span> <span class="toc-text">代码组合（compose）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A3%B0%E6%98%8E%E5%BC%8F%E7%9A%84%E4%BB%A3%E7%A0%81"><span class="toc-number">7.</span> <span class="toc-text">声明式的代码</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">8.</span> <span class="toc-text">总结</span></a></li></ol>
    </div>

    <div id="share-footer" style="display: none">
      <ul>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.facebook.com/sharer.php?u=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/"><i class="fab fa-facebook fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://twitter.com/share?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&text=函数式编程"><i class="fab fa-twitter fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.linkedin.com/shareArticle?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&title=函数式编程"><i class="fab fa-linkedin fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://pinterest.com/pin/create/bookmarklet/?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&is_video=false&description=函数式编程"><i class="fab fa-pinterest fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=函数式编程&body=Check out this article: https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/"><i class="fas fa-envelope fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://getpocket.com/save?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&title=函数式编程"><i class="fab fa-get-pocket fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://reddit.com/submit?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&title=函数式编程"><i class="fab fa-reddit fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.stumbleupon.com/submit?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&title=函数式编程"><i class="fab fa-stumbleupon fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://digg.com/submit?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&title=函数式编程"><i class="fab fa-digg fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.tumblr.com/share/link?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&name=函数式编程&description="><i class="fab fa-tumblr fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://news.ycombinator.com/submitlink?u=https://danyuan30.gitee.io/2022/02/05/JavaScript/functionalProgramming/&t=函数式编程"><i class="fab fa-hacker-news fa-lg" aria-hidden="true"></i></a></li>
</ul>

    </div>

    <div id="actions-footer">
        <a id="menu" class="icon" href="#" onclick="$('#nav-footer').toggle();return false;"><i class="fas fa-bars fa-lg" aria-hidden="true"></i> 菜单</a>
        <a id="toc" class="icon" href="#" onclick="$('#toc-footer').toggle();return false;"><i class="fas fa-list fa-lg" aria-hidden="true"></i> 目录</a>
        <a id="share" class="icon" href="#" onclick="$('#share-footer').toggle();return false;"><i class="fas fa-share-alt fa-lg" aria-hidden="true"></i> 分享</a>
        <a id="top" style="display:none" class="icon" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up fa-lg" aria-hidden="true"></i> 返回顶部</a>
    </div>

  </div>
</div>

        
        <footer id="footer">
  <div class="footer-left">
    Copyright &copy;
    
    
    2021-2022
    柯里的语法糖
  </div>
  <div class="footer-right">
    <nav>
      <ul>
        <!--
       --><li><a href="/">首页</a></li><!--
     --><!--
       --><li><a href="/tags/">标签</a></li><!--
     --><!--
       --><li><a href="/categories/">分类</a></li><!--
     --><!--
       --><li><a href="/archives/">归档</a></li><!--
     --><!--
       --><li><a target="_blank" rel="noopener" href="http://github.com/twitzz">项目</a></li><!--
     --><!--
       --><li><a href="/about/">关于</a></li><!--
     --><!--
       --><li><a href="/search/">搜索</a></li><!--
     -->
      </ul>
    </nav>
  </div>
</footer>

    </div>
    <!-- styles -->



  <link rel="preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" crossorigin="anonymous" onload="this.onload=null;this.rel='stylesheet'"/>


    <!-- jquery -->
 
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" crossorigin="anonymous"></script> 




<!-- clipboard -->

  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.7/clipboard.min.js" crossorigin="anonymous"></script> 
  
  <script type="text/javascript">
  $(function() {
    // copy-btn HTML
    var btn = "<span class=\"btn-copy tooltipped tooltipped-sw\" aria-label=\"复制到粘贴板!\">";
    btn += '<i class="far fa-clone"></i>';
    btn += '</span>'; 
    // mount it!
    $(".highlight table").before(btn);
    var clip = new ClipboardJS('.btn-copy', {
      text: function(trigger) {
        return Array.from(trigger.nextElementSibling.querySelectorAll('.code')).reduce((str,it)=>str+it.innerText+'\n','')
      }
    });
    clip.on('success', function(e) {
      e.trigger.setAttribute('aria-label', "复制成功!");
      e.clearSelection();
    })
  })
  </script>


<script src="/js/main.js"></script>

<!-- search -->

<!-- Google Analytics -->

<!-- Baidu Analytics -->

<!-- Cloudflare Analytics -->

<!-- Umami Analytics -->

<!-- Disqus Comments -->

<!-- utterances Comments -->

</body>
</html>
